#include <wx/sstream.h>

#include "MsnConnection.h"

#include "MsnTransport.h"

#include "MsnCommand.h"
#include "MsnMessenger.h"
#include "MsnContact.h"
#include "md5.h"
#include "Util.h"
#include "UserConfig.h"

#include "HTTPTransport.h"
#include "TCPTransport.h"
#include "CURLTransport.h"

MsnConnection::MsnConnection() : connectionType(0)
{
	transport = NULL;
    m_LastActive = wxDateTime::GetTimeNow();
}

MsnConnection::~MsnConnection()
{
	DEBUG(_T("~MsnConnection"));

	Destroy();
}

void MsnConnection::Open()
{
	if(connectionType == MSN_CONNECTION_DIRECT){
		transport = new TCPTransport();	
		transport->SetServerPort(MSN_TCP_SERVER_PORT);

	}else{
		transport = new CURLTransport();		
		transport->SetServerPort(Msn_HTTP_SERVER_PORT);
	}

	transport->SetServerAddress(serverAddress);
	transport->SetServerType(serverType);	
	
	transport->SetConnection(this);

	transport->Start();
}

void MsnConnection::Close()
{
	if(transport){
		transport->Close();
	}
}

void MsnConnection::Destroy()
{
	if(transport){
		transport->CloseAndDelete();
		wxDELETE(transport);
	}
}


void MsnConnection::ReConnect(const wxString& address, int port)
{
	//wxDELETE(transport);

	serverAddress = address;
	serverPort = port;

	transport->SetServerAddress(address);
	transport->SetServerPort(port);

	//transport->Close();	

	transport->Open();
}


bool MsnConnection::IsConnected()
{
	return transport->IsConnected();
}


void MsnConnection::SendCommand(MsnCommand& cmd)
{
    DEBUG(_T(">>>") + cmd.toString());

    wxMemoryBuffer buf;
    cmd.ToBuffer(buf);
    transport->SendData(buf.GetData(), buf.GetDataLen());

    m_LastActive = wxDateTime::GetTimeNow();
}

void MsnConnection::SendCommand(MsnCommand& cmd, const wxString& content)
{
    DEBUG(_T(">>>") + cmd.toString()+content);

    wxMemoryBuffer buf;
    cmd.ToBuffer(buf);

	
	buf.AppendData(content.mb_str(), content.Length());

    transport->SendData(buf.GetData(), buf.GetDataLen());

    m_LastActive = wxDateTime::GetTimeNow();
}




